<template>
    <div class = "moodtabel">
    <div id="jar-container">
        <div id="mood-container">
            <div v-for="mood in moods" :key="mood.moodId" @click="showModal(mood)"
                class="mood" :style="{ left: mood.position?.left + '%' , top: mood.position?.top + '%'}">
                {{ getMoodIcon(mood.moodName) }}
            </div>
        </div>
    </div>
    <div v-if="isModalVisible" id="modal" class="modal" :class="{ 'show': isModalVisible }" ref="modal">
        <div class="modal-content">
            <span class="close-button" @click="closeModal">×</span>
            <div class="info-section">
                <p class="date-info">{{formatDate(selectedPlace.visitTime)}}</p>
                <p class="event-info">事件: {{  selectedMood.tagName }}</p>
                <p class="location-info">地点: {{  selectedPlace.placeName }}</p>
                <p class="frequency-info"> Highest Frequency: {{ highestFrequency }} at {{ highestFrequencyLocation }}</p>
            </div>
        </div>
    </div>
    <div id="chat-container">
        <div id="chat-header">
            <div style="display: flex; align-items: center;">
            <img :src="avatarUrl" alt="智能心情助手" style="height: 50px; vertical-align: middle;">
            <span style="margin-left: 8px; font-size: 16px; font-weight: bold;">AI助手</span>
            </div>
        </div>
        <div id="chat-body">
            <p class="chat-message">你好！我是你的专属心情助手。告诉我你的心情，我可以建议一些活动和地点。</p>
            <div v-for="message in messages" :key="message.id" class="chat-message" :class="{ 'user-message': message.isUser, 'ai-message': !message.isUser }">
                {{ message.content }}
            </div>
        </div>
        <div id="chat-input">
            <input v-model="userInput" type="text" placeholder="输入你的心情..." />
            <button @click="sendMessage">发送</button>
        </div>
    </div>
    </div>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted, nextTick } from 'vue';

const avatarUrl = require('@/assets/头像.png');
const moods = reactive([]);
const messages = reactive([]);
const userInput = ref('');
const isModalVisible = ref(false);
const selectedMood = ref({});
const selectedPlace = ref({});
const highestFrequency = ref(1);
const highestFrequencyLocation = ref('3');
const modalRef = ref(null);


onMounted(async () => {
    await loadAllMoods();
    if (modalRef.value) {
        modalRef.value.querySelector('.close-button').addEventListener('click', closeModal);
    }
    nextTick(() => {
        setupMoodsPosition();
    });
});

function setupMoodsPosition() {
    moods.forEach(mood => {
        mood.position = { left: Math.random() * 100, top: Math.random() * 100 };  // 设置心情在容器内的随机位置
    });
}

async function loadAllMoods() {
    try {
        const response = await axios.get('/api/moods/all');
        moods.splice(0, moods.length, ...response.data.data);
    } catch (error) {
        console.error('Failed to load moods:', error);
    }
}

async function loadMoodAndPlace(moodId) {
    try {
        const moodResponse = await fetchMoodById(moodId);
        if (!moodResponse) {
            throw new Error('Mood data not found');
        }
        const placeResponse = await fetchPlaceById(moodResponse.placeId);
        if (!placeResponse) {
            throw new Error('Place data not found');
        }
        selectedMood.value = moodResponse;
        selectedPlace.value = placeResponse;
        await calculateFrequency(placeResponse.placeId);
    } catch (error) {
        console.error('Failed to load mood and place details:', error);
    }
}


async function fetchMoodById(moodId) {
    try {
        const response = await axios.get(`/api/moods/get`,{
        params: { moodId: moodId }}
        );
        return response.data.data;
    } catch (error) {
        console.error('Error fetching mood:', error);
        return null;
    }
}

async function fetchPlaceById(placeId) {
    const token = localStorage.getItem('userToken');
  try {
    const response = await axios.get(`/api/places/find`, {
      headers: {
        'Authorization': token
      },
      params: { placeId: placeId }
    });
    return response.data.data;
  } catch (error) {
    console.error('Error fetching place:', error);
    return null;
  }
}


async function calculateFrequency(placeId) {
    return placeId.placeName;
}

function closeModal() {
    isModalVisible.value = false;
}

function showModal(mood) {
    selectedMood.value = mood;
    isModalVisible.value = true;
    loadMoodAndPlace(mood.moodId);  
    nextTick(() => {
        if (modalRef.value) {
            const closeButton = modalRef.value.querySelector('.close-button');
            if (closeButton) {
                closeButton.addEventListener('click', closeModal);
            } else {
                console.error("Close button not found.");
            }
        } else {
            console.error("Modal not found.");
        }
    });
}

function formatDate(value) {
    if (!value) return '';
    return value.split('T')[0];
    }



function getMoodIcon(moodName) {
    switch (moodName) {
      case '开心':
        return '😀';
      case '伤心':
        return '😢';
      case '愤怒':
        return '😡';
      case '沮丧':
        return '😪';
      case '疲倦':
        return '🥱';
      default:
        return moodName;
    }
  }


  function analyzeMood(message) {
    const moodKeywords = {
        开心: ["开心", "愉悦", "高兴"],
        伤心: ["悲伤", "不开心", "低落"],
        生气: ["生气", "烦躁", "愤怒"],
        疲惫: ["累", "精疲力竭", "困"],
    };

    let detectedMood = 'neutral';
    Object.keys(moodKeywords).forEach(mood => {
        moodKeywords[mood].forEach(keyword => {
            if (message.toLowerCase().includes(keyword)) {
                detectedMood = mood;
            }
        });
    });
    return detectedMood;
}

function getRecommendations(mood) {
    const recommendations = {
    开心: { activities: ["去主题公园", "看喜剧表演"], places: ["当地公园", "电影院"] },
    伤心: { activities: ["去水疗中心", "在安静的咖啡馆读书"], places: ["水疗中心", "咖啡馆"] },
   生气: { activities: ["去健身房锻炼", "练习拳击"], places: ["健身房", "体育中心"] },
    疲惫: { activities: ["做按摩", "在休息室小憩"], places: ["按摩院", "休息室"] },
    neutral: { activities: ["探索当地市场", "参观博物馆"], places: ["市场", "博物馆"] },
};
    return recommendations[mood] || recommendations['neutral'];
}


  function sendMessage() {
    // Access the current value of userInput and check if it's not empty
    const trimmedMessage = userInput.value.trim();
    if (!trimmedMessage) {
        return; // Prevent sending an empty message
    }

    const userMood = analyzeMood(trimmedMessage);
    const { activities, places } = getRecommendations(userMood);

    messages.push({
                    id: messages.length + 1,
                    content: trimmedMessage, // Display content returned from the server
                    isUser: false,
                })
    messages.push({
        id: messages.length + 1,
        content: `根据你的心情，你可能会喜欢这些活动: ${activities.join(", ")}. 考虑参观这些地方: ${places.join(", ")}.`,
        isUser: true,
    }) 
    axios.post('/api/chat/send', { message: trimmedMessage })
        .then(response => {
            const responseData = response.data;
            if (responseData && responseData.data && responseData.code === 0) {
                messages.push({
                    id: messages.length + 1,
                    content: responseData.data.content, // Display content returned from the server
                    isUser: true 
                });
            } else {
                console.error('Received an error or invalid format:', responseData);
            }
        })
        .catch(error => {
            console.error('Error sending message:', error);
            messages.push({
                id: messages.length + 1,
                content: `错误：${error.message || "Failed to communicate with server"}`
            });
        })
        .finally(() => {
            userInput.value = ''; // Clear the input field after sending
        });
}
</script>

<style scoped>
@import "@/assets/css/Moodjar.css";
</style>


